<?php
/**
 * @author       Sixe Team
 * @email        info@eee-eee.com
 * @url          http://www.eee-eee.com
 * @copyright    Copyright (C) 2010 - 2019 Sixe Information Technology Limited. All rights reserved.
 * @license      GNU General Public License version 2 or later; see LICENSE.txt
 * @date         2019/10/01 10:00
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\Utilities\ArrayHelper;

// Base this model on the backend version.
JLoader::register('SixeWorkFlowModelArticle', JPATH_ADMINISTRATOR . '/components/com_sixeworkflow/models/article.php');

/**
 * Content Component Article Model
 *
 * @since  1.5
 */
class SixeWorkFlowModelArticleForm extends SixeWorkFlowModelArticle
{
	/**
	 * Model typeAlias string. Used for version history.
	 *
	 * @var        string
	 */
	public $typeAlias = 'com_content.article';

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication();

		// Load state from the request.
		$pk = $app->input->getInt('a_id');
		$this->setState('article.id', $pk);

		$this->setState('article.catid', $app->input->getInt('catid'));

		$return = $app->input->get('return', null, 'base64');
		$this->setState('return_page', base64_decode($return));

		// Load the parameters.
		$params = $app->getParams('com_content');
		$this->setState('params', $params);

		$this->setState('layout', $app->input->getString('layout'));
	}

	/**
	 * Method to get article data.
	 *
	 * @param   integer  $itemId  The id of the article.
	 *
	 * @return  mixed  Content item data object on success, false on failure.
	 */
	public function getItem($itemId = null)
	{
		$itemId = (int) (!empty($itemId)) ? $itemId : $this->getState('article.id');

		// Get a row instance.
		$table = $this->getTable();

		// Attempt to load the row.
		$return = $table->load($itemId);

		// Check for a table object error.
		if ($return === false && $table->getError())
		{
			$this->setError($table->getError());

			return false;
		}

		$properties = $table->getProperties(1);
		$value = ArrayHelper::toObject($properties, 'JObject');

		// Convert attrib field to Registry.
		$value->params = new Registry($value->attribs);

		// Compute selected asset permissions.
		$user   = JFactory::getUser();
		$userId = $user->get('id');
		$asset  = 'com_content.article.' . $value->id;

		// Check general edit permission first.
		if ($user->authorise('core.edit', $asset))
		{
			$value->params->set('access-edit', true);
		}

		// Now check if edit.own is available.
		elseif (!empty($userId) && $user->authorise('core.edit.own', $asset))
		{
			// Check for a valid user and that they are the owner.
			if ($userId == $value->created_by)
			{
				$value->params->set('access-edit', true);
			}
		}

		// Check edit state permission.
		if ($itemId)
		{
			// Existing item
			$value->params->set('access-change', $user->authorise('core.edit.state', $asset));
		}
		else
		{
			// New item.
			$catId = (int) $this->getState('article.catid');

			if ($catId)
			{
				$value->params->set('access-change', $user->authorise('core.edit.state', 'com_content.category.' . $catId));
				$value->catid = $catId;
			}
			else
			{
				$value->params->set('access-change', $user->authorise('core.edit.state', 'com_content'));
			}
		}

		$value->articletext = $value->introtext;

		if (!empty($value->fulltext))
		{
			$value->articletext .= '<hr id="system-readmore" />' . $value->fulltext;
		}

		// Convert the metadata field to an array.
		$registry = new Registry($value->metadata);
		$value->metadata = $registry->toArray();

		if ($itemId)
		{
			$value->tags = new JHelperTags;
			$value->tags->getTagIds($value->id, 'com_content.article');
			$value->metadata['tags'] = $value->tags;
		}

		$this->_item=$this->getFlowContent($value->id);
		if(isset($this->_item->flow))
		{
			$value->flow=$this->_item->flow;
		}
		else
		{
			$flow=$this->getFlow($value->catid,$value->created_by);
			if(count($flow)>0)
			{
				$value->flow=$flow[0];
			}
			else
			{
				$value->flow=0;
			}
			
		}
		
		$value->state=$this->_item->state;
		$value->start_flow=$this->_item->start_flow;
		$value->max_flow=$this->_item->max_flow;
		$value->message=$this->_item->message;
		return $value;
	}

	/**
	 * Get the return URL.
	 *
	 * @return  string	The return URL.
	 *
	 * @since   1.6
	 */
	public function getReturnPage()
	{
		return base64_encode($this->getState('return_page'));
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   3.2
	 */
	public function save($data)
	{
		// Associations are not edited in frontend ATM so we have to inherit them
		if (JLanguageAssociations::isEnabled() && !empty($data['id'])
			&& $associations = JLanguageAssociations::getAssociations('com_content', '#__content', 'com_content.item', $data['id']))
		{
			foreach ($associations as $tag => $associated)
			{
				$associations[$tag] = (int) $associated->id;
			}

			$data['associations'] = $associations;
		}

		return parent::save($data);
	}

	// add by adan20191210
	public function approval($data) {
		if(!isset($data['flowstate']))
		{
			$data['flowstate']=$data['state'];
		}
		if(!isset($data['flow']))
		{
			$data['flow']=0;
		}
		if($data['flowstate']==1)
		{
			$data['state']=1;
		}
		else
		{
			$data['state']=10;
		}

		$return = $this->saveFlowArticle($data['id'],$data);
		if ($return) {
			$db = JFactory::getDBO();
			$query = $db->getQuery(true)
				->update('#__content')
				->set('state='.$db->q($data['state']))
				->where('id='.$db->q($data['id']));
			$db->setQuery($query)->execute();
		}

		return $return;
	}

	/**
	 * Allows preprocessing of the JForm object.
	 *
	 * @param   JForm   $form   The form object
	 * @param   array   $data   The data to be merged into the form object
	 * @param   string  $group  The plugin group to be executed
	 *
	 * @return  void
	 *
	 * @since   3.7.0
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'content')
	{
		return parent::preprocessForm($form, $data, $group);
	}


	public function getIs_Add()
	{
		$is_add=false;
		$user=JFactory::getUser();
		$groups=implode(',',$user->groups);
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select('COUNT(DISTINCT a.workflow_id)')
			  ->from('#__workflow_users AS a')
			  ->where('(a.type=1 AND a.user_id IN ('.$groups.')) OR (a.type=2 AND a.user_id='.$user->id.')');
			  $db->setQuery($query);
			  $is_add = $db->loadResult();
		return $is_add;
	}

	public function getEditAccess($id)
	{
		$return=false;
		$user=JFactory::getUser();
		$groups=implode(',',$user->groups);
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select('COUNT(*)')
			  ->from('#__workflow_flows AS a')
			  ->where('a.content_id='.$id)
			  ->where('a.user_id='.$user->id);
			  $db->setQuery($query);
			  $return = $db->loadResult();
			  if(false)
			  {
			  	return $return;
			  }
			  else
			  {
			  	$query = $db->getQuery(true);
			  	$query->select('COUNT(DISTINCT c.content_id)');
			  	$query->from('#__workflow_contents AS c')
			  	->where('c.content_id='.$id)
				//->where('(SELECT COUNT(*) FROM #__workflow_flows WHERE content_id=c.content_id AND flow_id=c.flow) = 0')
				->join('INNER','#__workflow_categories AS wc ON wc.category_id=c.catid')
				->join('INNER','#__workflow_users AS wu ON wu.workflow_id = wc.workflow_id')
		   		->where('(c.created_by='.$user->id.' OR (((wu.type=1 AND wu.user_id IN ('.$groups.') AND wu.flow_id=c.flow) OR (wu.type=2 AND wu.user_id='.$user->id.' AND wu.flow_id=c.flow)) AND c.flow > c.start_flow))');
		   		$db->setQuery($query);
			 	$content = $db->loadResult();
			 	if($content > 0)
			 	{
			 		$return=true;
			 	}

			  }
		

		return $return;
		}
	public function checkin($pk = null)
	{
		// Only attempt to check the row in if it exists.
		if ($pk)
		{
			$user = \JFactory::getUser();

			// Get an instance of the row to checkin.
			$table = $this->getTable();

			if (!$table->load($pk))
			{
				$this->setError($table->getError());

				return false;
			}

			$checkedOutField = $table->getColumnAlias('checked_out');
			$checkedOutTimeField = $table->getColumnAlias('checked_out_time');

			// If there is no checked_out or checked_out_time field, just return true.
			if (!property_exists($table, $checkedOutField) || !property_exists($table, $checkedOutTimeField))
			{
				return true;
			}

			// Check if this is the user having previously checked out the row.
			if ($table->{$checkedOutField} > 0 && $table->{$checkedOutField} != $user->get('id') && !$user->authorise('core.admin', 'com_checkin'))
			{
				$this->setError(\JText::_('JLIB_APPLICATION_ERROR_CHECKIN_USER_MISMATCH'));

				//return false;
			}

			// Attempt to check the row in.
			if (!$table->checkIn($pk))
			{
				$this->setError($table->getError());

				return false;
			}
		}

		return true;
	}
}
